#include <buola/widgets/chandlebar.h>
#include <buola/widgets/ctheme.h>
#include <buola/widgets/cbutton.h>

namespace buola { namespace gui {

///////////////////////////
///////// SHandle /////////
///////////////////////////

CHandleBar::CHandleBar()
    :   mMoving(false)
    ,   mOverArea(CTheme::DECO_NONE)
{
    get_default_theme()->PrepareHandleBar(this);
}

CHandleBar::~CHandleBar()
{
}

void CHandleBar::SetCaption(const std::wstring &pCaption)
{
    mCaption=pCaption;
    Refresh();
}

CTheme::EDecoFlags CHandleBar::GetArea(const CPoint_d &pPos)
{
    if(!GetStyle(STYLE_WHOLEBAR))
        return CTheme::DECO_NONE;

    if(CRect_d(CPoint_d(Size().x-18,Size().y/2-6),CSize_d(12,12)).Contains(pPos))
    {
        return CTheme::DECO_CLOSE;
    }
    else if(CRect_d(CPoint_d(Size().x-36,Size().y/2-6),CSize_d(12,12)).Contains(pPos))
    {
        return CTheme::DECO_DOCK;
    }
    else if(CRect_d(CPoint_d(Size().x-54,Size().y/2-6),CSize_d(12,12)).Contains(pPos))
    {
        return CTheme::DECO_MIN;
    }
    return CTheme::DECO_NONE;
}

///////////////// events //////////////////

void CHandleBar::OnSize(const CGeometryEvent &pE)
{
}

void CHandleBar::OnExpose(const CExposeEvent &pE)
{
    if(GetStyle(STYLE_WHOLEBAR))
    {
        CTheme::EDecoFlags lFlags=CTheme::DECO_NONE;
        if(mMoving)
            lFlags|=CTheme::DECO_ACTIVE;
        get_default_theme()->DrawHandleBar(pE.mGC,CRect_d({0,0},Size()),mCaption,lFlags,mOverArea);
    }
    else
    {
        get_default_theme()->DrawHandle(pE.mGC,CRect_d({0,0},Size()));
    }
}

void CHandleBar::OnButtonDown(const CMouseEvent &pE)
{
    if(pE.mButton==EMouseButton::LEFT)
    {
        mPressedArea=GetArea(pE.mPoint);
        if(mPressedArea==CTheme::DECO_NONE)
        {
            mMoving=true;
            Refresh(true);
            sStartMove(pE.mRootPoint);
        }
    }
}

void CHandleBar::OnButtonUp(const CMouseEvent &pE)
{
    if(pE.mButton==EMouseButton::LEFT)
    {
        if(mMoving)
        {
            mMoving=false;
            sEndMove();

            Refresh(true);
        }
        else if(mPressedArea==GetArea(pE.mPoint))
        {
            if(mPressedArea==CTheme::DECO_CLOSE)
                eClose();
            else if(mPressedArea==CTheme::DECO_DOCK)
                eDock();
        }
        mPressedArea=CTheme::DECO_NONE;
    }
}

void CHandleBar::OnMouseMove(const CMouseEvent &pE)
{
    if(mMoving)
    {
        sContinueMove(pE.mRootPoint);
    }
    else
    {
        CTheme::EDecoFlags lArea=GetArea(pE.mPoint);
        if(lArea!=mOverArea)
        {
            mOverArea=lArea;
            Refresh();
        }
    }
}

void CHandleBar::OnMouseOut(const CMouseEvent &pE)
{
    if(mOverArea!=CTheme::DECO_NONE)
    {
        mOverArea=CTheme::DECO_NONE;
        Refresh();
    }
}

/*namespace gui*/ } /*namespace buola*/ }
